import { AddData, SavedData } from "../utils/data";
import eventSettings from "../utils/eventSettings";
import { location } from "../utils/getLocation";
import { DrawString } from "../utils/utils";
import { InstanceStats } from "./dungeon";
import { joininstance } from "./partycommand";

class PopupEvents {

    Ding_Sound = {source:"Ding.ogg",priority:true,category:"master",volume:1,attenuation:2};

    title = "";
    text = "";
    timeStamp = 0;
    time = 0;
    cmd = "";

    RegExps = {
        partyInvite : /------------------------------------------------------>newLine<-(\[[\w+\+-]+] )?([0-9a-zA-Z_]{2,24})( has invited you to join | has invited all members of .+ to |邀请你加入|已邀请.+中的所有成员加入)(.+)( party!|组队！)->newLine<-(You have 60 seconds to accept. Click here to join!|你有60秒时间接受。点击这里以加入！)->newLine<------------------------------------------------------/i,
        friendRequest : /------------------------------------------------------>newLine<-(Friend request from |好友请求： )(\[[\w+\+-]+] )?([0-9a-zA-Z_]{2,24})->newLine<-(\[ACCEPT\] - \[DENY\] - \[BLOCK\]|\[接受\] - \[拒绝\] - \[BLOCK\])->newLine<------------------------------------------------------/i,
        skyblockTrade : /([0-9a-zA-Z_]{2,24}) has sent you a trade request. Click here to accept!/i,
        duelsRequest : /------------------------------------------------------>newLine<-[ ]+(\[[\w+\+-]+] )?([0-9a-zA-Z_]{2,24})( has invited you to |邀请你参与)(.+)[!！]->newLine<-[ ]+(CLICK HERE to accept! You have 60 seconds to accept.|点击这里来接受！邀请有效时间为60秒。)->newLine<------------------------------------------------------/i,
        dungeonRestart : /(组队|組隊|Party) > (\[[\w+\+-]+] )?([0-9a-zA-Z_]+)( [♲Ⓑ☀⚒ቾ]+)?: rs/i
    }
    
    constructor() {
        AddData("keybindPopupEventsYes",0);
        AddData("keybindPopupEventsNo",0);
        this.keybindYes = new KeyBind("弹出事件 - 确认",SavedData.keybindPopupEventsYes,"BabayzombieAddons - ChatTriggers Module");
        this.keybindNo = new KeyBind("弹出事件 - 取消",SavedData.keybindPopupEventsNo,"BabayzombieAddons - ChatTriggers Module");
        this.init();
    }

    popupNotifications(title,text,cmd,time=10) {
        this.title = title;
        this.text = text;
        this.timeStamp = Date.now() + time * 1000;
        this.time = time * 1000;
        this.cmd = cmd;
    }

    closeNotifications() {
        this.title = "";
        this.text = "";
        this.timeStamp = 0;
        this.time = 0;
        this.cmd = "";
    }

    drawStringAtMidScreen(text,y,s) {
        let x = Renderer.screen.getWidth() / 2;
        let width = Renderer.getStringWidth(text);
        DrawString(text, x - width / 2 * s, y, s, true);
    }

    drawStringAtScreen(text,x,y,s,width) {
        let totalWidth = 0;
        let newString = "";
        let stringHeight = 1;
        for (let i = 0; i < text.length; i++) {
            totalWidth += Renderer.getStringWidth(text[i]);
            if(totalWidth > width) {
                newString += "\n";
                stringHeight++;
                totalWidth = Renderer.getStringWidth(text[i]);
            }
            newString += text[i];
        }
        DrawString(newString, x, y, s, true);
        let yesorno = (this.keybindYes.getKeyCode() ? `§a[${Keyboard.getKeyName(this.keybindYes.getKeyCode())}] 接受` : "") + (this.keybindYes.getKeyCode() && this.keybindNo.getKeyCode() ? "   " : "") + (this.keybindNo.getKeyCode() ? `§e[${Keyboard.getKeyName(this.keybindNo.getKeyCode())}] 忽略` : "");
        DrawString(yesorno, x + width - Renderer.getStringWidth(yesorno), Renderer.screen.getHeight() / 8 + 35, s, true);
    }

    init() {
        this.keybindYes.registerKeyPress(() => {
            if (this.cmd != "" && this.timeStamp > Date.now()) ChatLib.command(this.cmd);
            this.closeNotifications();
        })
        this.keybindNo.registerKeyPress(this.closeNotifications())

        register("gameUnload", () => {
            SavedData.keybindPopupEventsYes = this.keybindYes.getKeyCode();
            SavedData.keybindPopupEventsNo = this.keybindNo.getKeyCode();
        })

        register("chat", (message,event) => {
            if(location.server == "") return;
            for (let regs in this.RegExps) {
                if(!this.RegExps[regs].test(message)) continue;
                let args = this.RegExps[regs].exec(message);
                switch (regs) {
                    case "partyInvite":
                        let playername = args[2];
                        if(args[3].includes("all members") || args[3].includes("所有成员")) {
                            if(eventSettings.popupPartyInvite) {
                                this.popupNotifications("§b公会组队邀请",`§b${playername} §e邀请公会里的所有成员加入${args[4]}组队`,`party accept ${playername}`);
                                new Sound(this.Ding_Sound).play();
                            }
                        } else 
                        if(eventSettings.popupGuildPartyInvite) {
                            this.popupNotifications("§b组队邀请",`§b${playername} §e邀请你加入${args[4]}组队`,`party accept ${playername}`);
                            new Sound(this.Ding_Sound).play();
                        }
                        break;
                    case "friendRequest":
                        if(eventSettings.popupFriendRequest) {
                            let playername2 = args[3];
                            this.popupNotifications("§a好友请求",`§b${playername2} §a请求添加你为好友`,`friend accept ${playername2}`);
                            new Sound(this.Ding_Sound).play();
                        }
                        break;
                    case "skyblockTrade":
                        if(eventSettings.popupSkyblockTrade && location.inSkyblock) {
                            let playername3 = args[1];
                            if(location.island == "The Rift") this.popupNotifications("§6Skyblock交换请求",`§b${playername3} §6想要和你交换位置`,`trade ${playername3}`);
                             else this.popupNotifications("§6Skyblock交易请求",`§b${playername3} §6想要和你进行交易`,`trade ${playername3}`);
                            new Sound(this.Ding_Sound).play();
                            }
                        break;
                    case "duelsRequest":
                        if(eventSettings.popupDuelsRequest) {
                            let playername4 = args[2];
                            this.popupNotifications("§6决斗邀请",`§b${playername4} §6邀请你进行 §b${args[4]} §6决斗`,`duels accept ${playername4}`);
                            new Sound(this.Ding_Sound).play();
                        }
                        break;
                    case "dungeonRestart":
                        if(eventSettings.popupDungeonRestart && location.inSkyblock && (location.inDungeon || location.inKuudra) && InstanceStats.leader) {
                            let playername5 = args[3];
                            let floor = location.location.removeFormatting().split("(")[1].split(")")[0].toLowerCase();
                            this.popupNotifications(`§6${(location.inDungeon ? "地牢" : "Kuudra")}重开请求`,`§b${playername5} §6希望重新开始一局${(location.inDungeon ? "地牢" : "Kuudra")}`,joininstance(floor[0],floor[1]));
                            new Sound(this.Ding_Sound).play();
                        }
                        break;
                }
            }
        }).setCriteria("${message}")

        register("renderOverlay", () => {
            if(this.timeStamp <= Date.now()) {
                this.closeNotifications();
                return;
            }
            Renderer.drawRect(Renderer.color(0, 0, 0, 150), Renderer.screen.getWidth() / 2 - 76, Renderer.screen.getHeight() / 8 - 1, 152, 52);
            this.drawStringAtMidScreen(this.title, Renderer.screen.getHeight() / 8, 2 / 1.2);
            this.drawStringAtScreen(this.text, Renderer.screen.getWidth() / 2 - 75, Renderer.screen.getHeight() / 8 + 13 * 2 / 1.5, 1, 150);
            Renderer.drawRect(Renderer.color(255, 255, 255, 70), Renderer.screen.getWidth() / 2 - 76, Renderer.screen.getHeight() / 8 + 45, 150 * ((this.time - (this.timeStamp - Date.now())) / this.time), 6);
        });
    }
    
}

export default new PopupEvents();